package com.fire.market.service.impl;


import com.fire.component.extension.Assert;
import com.fire.market.gateway.api.request.UserLoginParam;
import com.fire.market.gateway.api.request.UserRegisterParam;
import com.fire.market.utils.MD5Utils;
import com.fire.market.entity.UserInfoDo;
import com.fire.market.manager.UserManager;
import com.fire.market.model.UserModel;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class UserCmdCoreServiceImpl implements UserCmdCoreService {
    @Resource
    private UserManager userManager;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void register(UserRegisterParam param) {
        Assert.notNull(param, "userInfo is null");
        //验证手机号的验证码
        userManager.verify(param.getTelphone(), param.getOptCode());
        //保存User到数据库
        UserModel userModel = new UserModel();
        userModel.setName(param.getName());
        userModel.setGender(param.getGender());
        userModel.setAge(param.getAge());
        userModel.setTelphone(param.getTelphone());
        userModel.setRegisterMode("byPhone");
        //对密码加密
        String encodePassword = null;
        try {
            encodePassword = MD5Utils.getMD5Str(param.getPassword());
        } catch (Exception e) {
            throw new RuntimeException("MD5 Exception");
        }
        userModel.setEncrptPassword(encodePassword);
        userManager.saveUserInfo(userModel);
    }

    @Override
    public UserInfoDo login(UserLoginParam param) {
        Assert.notNull(param, "UserLoginParam is null");
        Assert.notNull(param.getPassword(), "password is null");
        Assert.notNull(param.getTelephone(),"telephone is null");
        //对密码加密
        String encodePassword = null;
        try {
            encodePassword = MD5Utils.getMD5Str(param.getPassword());
        } catch (Exception e) {
            throw new RuntimeException("MD5 Exception");
        }
       return userManager.login(param.getTelephone(), encodePassword);
    }
}
